//
//  MenuView.swift
//  CMB250716
//
//  Created by Andy Lau on 16/7/25.
//

import Foundation
import SwiftUI
#if canImport(UIKit)
import UIKit
#endif

struct MenuView: View {
    @EnvironmentObject var dataManager: DataManager
    @State private var selectedCategory: MenuCategory = .recommended
    @State private var searchText = ""
    @State private var selectedItem: MenuItem?
    @State private var isUserScrolling = false // 标记用户是否正在手动滚动
    
    // 按品类分组的菜品数据
    var groupedItems: [(category: MenuCategory, items: [MenuItem])] {
        if searchText.isEmpty {
            // 无搜索时，显示所有品类的菜品
            return MenuCategory.allCases.compactMap { category in
                let items = dataManager.menuItems.filter { $0.category == category }
                return items.isEmpty ? nil : (category: category, items: items)
            }
        } else {
            // 有搜索时，只显示当前选中品类的搜索结果
            let categoryItems = dataManager.menuItems.filter { $0.category == selectedCategory }
            let filteredItems = categoryItems.filter { item in
                let name = dataManager.currentLanguage == "zh" ? item.name : item.englishName
                return name.localizedCaseInsensitiveContains(searchText) ||
                       item.description.localizedCaseInsensitiveContains(searchText)
            }
            return filteredItems.isEmpty ? [] : [(category: selectedCategory, items: filteredItems)]
        }
    }
    
    // 扁平化的所有菜品列表（用于滚动位置计算）
    var allItems: [MenuItem] {
        return groupedItems.flatMap { $0.items }
    }
    
    var body: some View {
        NavigationView {
            VStack(spacing: 8) {
                // 顶部工具栏（搜索框、语言选择、购物车）
                topToolbar
                
                // 分类选择器
                categorySelector
                
                // 菜品列表
                menuItemsList
            }
            .background(
                Image("LoginBackground")
                    .resizable()
                    .scaledToFill()
                    .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
                    .edgesIgnoringSafeArea(.all)
            )
            .zIndex(0) // 确保内容在背景之上
            .navigationTitle("")
            .navigationBarTitleDisplayMode(.inline)
            .dismissKeyboardOnBackgroundTap() // 添加点击背景收起键盘功能
        }
        .sheet(item: $selectedItem, onDismiss: { selectedItem = nil }) { item in
            MenuItemDetailView(item: item)
                .environmentObject(dataManager)
        }
        // 购物车冲突alert已移除，现在使用自动替换逻辑
    }
    
    // MARK: - 顶部工具栏
    private var topToolbar: some View {
        HStack(spacing: 12) {
            // 搜索框（缩短版）
            HStack {
                Image(systemName: "magnifyingglass")
                    .foregroundColor(.gray)
                    .font(.system(size: 16))
                
                TextField(
                    dataManager.currentLanguage == "zh" ? AppStrings.Menu.searchDishes : AppStrings.Menu.searchDishesEn,
                    text: $searchText
                )
                .foregroundColor(.white)
                .font(.system(size: 16))
                
                if !searchText.isEmpty {
                    Button(action: {
                        searchText = ""
                    }) {
                        Image(systemName: "xmark.circle.fill")
                            .foregroundColor(.gray)
                            .font(.system(size: 14))
                    }
                }
            }
            .padding(8)
            .background(Color.black.opacity(0.3))
            .cornerRadius(8)
            
            // 刷新按钮
            Button(action: {
                // 调用DataManager的刷新方法
                dataManager.refreshMenuItems()
            }) {
                Image(systemName: "arrow.clockwise")
                    .foregroundColor(.white)
                    .font(.system(size: 18))
                    .padding(8)
                    .background(Color.black.opacity(0.3))
                    .cornerRadius(8)
            }
            
            // 语言选择按钮
            Button(action: {
                dataManager.switchLanguage()
            }) {
                Image(systemName: "globe")
                    .font(.system(size: 20))
                    .foregroundColor(Color(red: 1.0, green: 0.5, blue: 0.0))
            }
            .padding(8)
            .background(
                Circle()
                    .fill(Color(red: 0.2, green: 0.2, blue: 0.2))
            )
            
            // 购物车按钮
            NavigationLink(destination: CartView()) {
                ZStack {
                    Image(systemName: "cart.fill")
                        .font(.system(size: 20))
                        .foregroundColor(Color(red: 1.0, green: 0.5, blue: 0.0))
                    
                    if dataManager.cartItemCount > 0 {
                        Text("\(dataManager.cartItemCount)")
                            .font(.caption2)
                            .fontWeight(.bold)
                            .foregroundColor(.white)
                            .padding(4)
                            .background(Circle().fill(Color.red))
                            .offset(x: 10, y: -10)
                    }
                }
            }
            .padding(8)
            .background(
                Circle()
                    .fill(Color(red: 0.2, green: 0.2, blue: 0.2))
            )
        }
        .padding(.horizontal, 12)
        .padding(.vertical, 8)
        .background(
            RoundedRectangle(cornerRadius: 8)
                .fill(Color(red: 0.2, green: 0.2, blue: 0.2))
        )
    }
    
    // MARK: - 分类选择器
    private var categorySelector: some View {
        ScrollViewReader { proxy in
            ScrollView(.horizontal, showsIndicators: false) {
                HStack(spacing: 15) {
                    ForEach(Array(MenuCategory.allCases), id: \.self) { category in
                        CategoryButton(category: category, selectedCategory: selectedCategory) {
                            selectedCategory = category
                        }
                        .id("category_button_\(category.rawValue)")
                    }
                }
                .padding(.horizontal, 20)
            }
            .padding(.vertical, 10)
            .onChange(of: selectedCategory) { newCategory in
                // 当选中品类改变时，自动滚动导航栏让该品类按钮可见
                withAnimation(.easeInOut(duration: 0.3)) {
                    proxy.scrollTo("category_button_\(newCategory.rawValue)", anchor: .center)
                }
            }
        }
    }
    
    // MARK: - 菜品列表
    private var menuItemsList: some View {
        ScrollViewReader { scrollProxy in
            ScrollView {
                LazyVStack(spacing: 10) {
                    ForEach(groupedItems, id: \.category) { categoryGroup in
                        // 该品类下的菜品
                        ForEach(categoryGroup.items.enumerated().map { IndexedItem(index: $0.offset, item: $0.element) }, id: \.item.id) { indexedItem in
                            MenuItemRowView(item: indexedItem.item) { selected in
                                selectedItem = selected
                            }
                            .id(indexedItem.index == 0 ? "category_\(indexedItem.item.category.rawValue)" : "item_\(indexedItem.item.id)")
                            .background(
                                // 只在每个类别的第一个菜品上添加位置检测
                                indexedItem.index == 0 ? 
                                GeometryReader { geometry in
                                    Color.clear
                                        .onAppear {
                                            updateVisibleCategory(for: indexedItem.item.category, 
                                                                 yPosition: geometry.frame(in: .named("scroll")).minY)
                                        }
                                        .onChange(of: geometry.frame(in: .named("scroll")).minY) { yPosition in
                                            updateVisibleCategory(for: indexedItem.item.category, yPosition: yPosition)
                                        }
                                } : nil
                            )
                        }
                    }
                }
                .padding(.horizontal, 8)
                .padding(.bottom, 100)
            }
            .coordinateSpace(name: "scroll")
            .onChange(of: selectedCategory) { newCategory in
                // 当类别改变时，滚动到该类别的第一个菜品
                // 只在无搜索状态下执行滚动
                guard searchText.isEmpty else { return }
                
                // 标记为用户点击导航栏触发的滚动
                isUserScrolling = true
                
                // 使用更平滑的动画滚动到指定类别的第一个菜品
                withAnimation(.easeOut(duration: 0.3)) {
                    scrollProxy.scrollTo("category_\(newCategory.rawValue)", anchor: .top)
                }
                
                // 延迟重置滚动标记
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                    isUserScrolling = false
                }
            }
        }
    }
    
    // MARK: - 辅助方法
    
    /// 根据类别位置更新当前选中的品类
    private func updateVisibleCategory(for category: MenuCategory, yPosition: CGFloat) {
        // 只在无搜索状态下且非用户点击导航栏时进行自动品类切换
        guard searchText.isEmpty && !isUserScrolling else { return }
        
        // 当类别进入可见区域时切换选中状态
        let visibleThreshold: CGFloat = 100 // 距离顶部100点以内的类别被认为是可见的
        
        if yPosition <= visibleThreshold && yPosition >= -50 && category != selectedCategory {
            withAnimation(.easeInOut(duration: 0.2)) {
                selectedCategory = category
            }
        }
    }


// MARK: - Category Button
struct CategoryButton: View {
    let category: MenuCategory
    let selectedCategory: MenuCategory
    let action: () -> Void
    @EnvironmentObject var dataManager: DataManager
    
    private var isSelected: Bool {
        selectedCategory == category
    }
    
    var body: some View {
        Button(action: action) {
            Text(dataManager.currentLanguage == "zh" ? category.rawValue : category.englishName)
                .font(.system(size: 16, weight: isSelected ? .semibold : .medium))
                .foregroundColor(isSelected ? Color.white : Color(red: 1.0, green: 0.5, blue: 0.0))
                .padding(.horizontal, 16)
                .padding(.vertical, 6)
                .background(
                    RoundedRectangle(cornerRadius: 20)
                        .fill(isSelected ? 
                            Color(red: 1.0, green: 0.5, blue: 0.0) : 
                            Color.clear
                        )
                        .overlay(
                            RoundedRectangle(cornerRadius: 20)
                                .stroke(isSelected ? 
                                    Color.clear : 
                                    Color(red: 1.0, green: 0.5, blue: 0.0), 
                                    lineWidth: 1.5
                                )
                        )
                )
                .shadow(
                    color: isSelected ? Color(red: 0.8, green: 0.7, blue: 0.4).opacity(0.3) : Color.clear,
                    radius: 4,
                    x: 0,
                    y: 2
                )
                .animation(.easeInOut(duration: 0.2), value: isSelected)
        }
        .padding(.horizontal, 5)
    }
}

// MARK: - 辅助结构
struct IndexedItem {
    let index: Int
    let item: MenuItem
}

// MARK: - 菜品行视图
struct MenuItemRowView: View {
    let item: MenuItem
    let onSelect: (MenuItem) -> Void
    @EnvironmentObject var dataManager: DataManager
    @State private var showingAddToCart = false
    
    // 计算当前商品在购物车中的数量
    private var itemQuantityInCart: Int {
        dataManager.getItemQuantityInCart(item)
    }
    
    // 判断是否已选中（数量大于0）
    private var isItemSelected: Bool {
        itemQuantityInCart > 0
    }
    
    var body: some View {
        GeometryReader { geometry in
            let screenWidth = geometry.size.width
            let mainContent = HStack(spacing: 10) {
                itemImageButton
                
                VStack(alignment: .leading, spacing: 6) {
                     itemTitleSection
                     
                     HStack(alignment: .top, spacing: 8) {
                         itemDescription
                             .frame(maxWidth: .infinity, alignment: .leading)
                         
                         VStack(alignment: .trailing, spacing: 4) {
                             Text("S$\(item.displayPrice, specifier: "%.2f")")
                                 .font(.title3)
                                 .fontWeight(.bold)
                                 .foregroundColor(Color(red: 1.0, green: 0.9, blue: 0.0))
                             
                             QuantitySelector(item: item)
                         }
                         .frame(width: screenWidth * 0.25)
                     }
                 }
                 .frame(maxWidth: .infinity, alignment: .leading)
            }
            
            mainContent
                .padding(10)
                .background(dynamicItemBackground)
                .opacity(item.isAvailable ? 1.0 : 0.6)
                .overlay(soldOutOverlay)
        }
        .frame(height: 160)
        .alert(isPresented: $showingAddToCart) {
            Alert(
                title: Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.addedToCart : AppStrings.Menu.addedToCartEn),
                message: Text(dataManager.currentLanguage == "zh" ? item.name : item.englishName),
                dismissButton: .default(Text(AppStrings.Common.confirm))
            )
        }
    }
    
    private var itemImageButton: some View {
        Button {
                onSelect(item)
            } label: {
            MenuItemImageView(
                imageSource: item.bestImageSource,
                width: 180,
                height: 140,
                cornerRadius: 16
            )
        }
        .buttonStyle(PlainButtonStyle())
    }
    
    private var itemTitleSection: some View {
        Button {
            onSelect(item)
        } label: {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? item.name : item.englishName)
                    .font(.headline)
                    .fontWeight(.bold)
                    .foregroundColor(Color(red: 1.0, green: 0.5, blue: 0.0))
                    .lineLimit(1)
                    .truncationMode(.tail)
                    .frame(maxWidth: .infinity, alignment: .leading)
                
                itemTags
            }
        }
        .buttonStyle(PlainButtonStyle())
    }
    

    
    private var itemTags: some View {
        HStack(spacing: 5) {
            if item.isSpicy {
                Image(systemName: "flame.fill")
                    .font(.caption)
                    .foregroundColor(.red)
            }
            
            // 对于饮品类别，只显示酒精饮品标识
            if item.category == .drinks, let drinkType = item.drinkType, drinkType == .alcoholic {
                Image(systemName: "wineglass.fill")
                    .font(.caption)
                    .foregroundColor(.purple)
            }
            // 对于非饮品类别，仍然显示素食标识
            else if item.category != .drinks && item.isVegetarian {
                Image(systemName: "leaf.fill")
                    .font(.caption)
                    .foregroundColor(.green)
            }
        }
    }
    
    private var itemDescription: some View {
        Text(dataManager.currentLanguage == "zh" ? item.description : item.englishDescription)
            .font(.subheadline)
            .foregroundColor(.white.opacity(0.9))
            .fontWeight(.medium)
            .lineLimit(3)
            .truncationMode(.tail)
            .frame(maxWidth: .infinity, alignment: .leading)
            .multilineTextAlignment(.leading)
    }
    
    private var itemPriceRow: some View {
        EmptyView()
    }
    
    // 默认背景样式
    private var defaultItemBackground: some View {
        RoundedRectangle(cornerRadius: 15)
            .fill(
                LinearGradient(
                    colors: [
                        Color(red: 0.15, green: 0.15, blue: 0.15),
                        Color(red: 0.1, green: 0.1, blue: 0.1),
                        Color(red: 0.05, green: 0.05, blue: 0.05)
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
            )
            .overlay(
                RoundedRectangle(cornerRadius: 15)
                    .stroke(
                        LinearGradient(
                            colors: [
                                Color(red: 0.7, green: 0.8, blue: 0.9).opacity(0.3),
                                Color(red: 0.9, green: 0.85, blue: 0.7).opacity(0.4)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ),
                        lineWidth: 1
                    )
            )
            .shadow(
                color: Color(red: 0.8, green: 0.7, blue: 0.4).opacity(0.2),
                radius: 8,
                x: 0,
                y: 4
            )
    }
    
    // 选中状态的背景样式（黑金、深紫、深亮橘橙色渐变）
    private var selectedItemBackground: some View {
        RoundedRectangle(cornerRadius: 15)
            .fill(
                LinearGradient(
                    colors: [
                        Color(red: 0.1, green: 0.1, blue: 0.1),      // 黑色
                        Color(red: 0.8, green: 0.6, blue: 0.2),      // 金色
                        Color(red: 0.4, green: 0.2, blue: 0.6),      // 深紫色
                        Color(red: 1.0, green: 0.4, blue: 0.1)       // 深亮橘橙色
                    ],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                )
            )
            .overlay(
                RoundedRectangle(cornerRadius: 15)
                    .stroke(
                        LinearGradient(
                            colors: [
                                Color(red: 1.0, green: 0.8, blue: 0.0),  // 金色光晕
                                Color(red: 1.0, green: 0.9, blue: 0.2)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ),
                        lineWidth: 2
                    )
            )
            .shadow(
                color: Color(red: 1.0, green: 0.8, blue: 0.0).opacity(0.6), // 金色光晕特效
                radius: 12,
                x: 0,
                y: 0
            )
            .shadow(
                color: Color(red: 1.0, green: 0.8, blue: 0.0).opacity(0.3),
                radius: 20,
                x: 0,
                y: 0
            )
    }
    
    // 动态背景，根据选中状态切换
    private var dynamicItemBackground: some View {
        Group {
            if isItemSelected {
                selectedItemBackground
                    .animation(.easeInOut(duration: 0.3), value: isItemSelected)
            } else {
                defaultItemBackground
                    .animation(.easeInOut(duration: 0.3), value: isItemSelected)
            }
        }
    }
    
    private var soldOutOverlay: some View {
        Group {
            if !item.isAvailable {
                Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.soldOut : AppStrings.Menu.soldOutEn)
                    .font(.caption)
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                    .padding(.horizontal, 8)
                    .padding(.vertical, 4)
                    .background(
                        RoundedRectangle(cornerRadius: 6)
                            .fill(Color.red)
                    )
                    .offset(x: 60, y: -30)
            }
        }
    }
}

// MARK: - 菜品详情视图
struct MenuItemDetailView: View {
    let item: MenuItem
    @EnvironmentObject var dataManager: DataManager
    @Environment(\.dismiss) var dismiss
    @State private var quantity = 1
    @State private var selectedMeatType: MeatType?
    @State private var selectedSpicyLevel: SpicyLevel?
    @State private var selectedPriceOption: PriceOption?
    @State private var specialInstructions = ""
    @State private var showingAddedAlert = false
    @State private var safeAreaTop: CGFloat = 0
    
    var body: some View {
        ZStack {
            // 背景
            LinearGradient(
                colors: [
                    Color(red: 0.12, green: 0.12, blue: 0.12),
                    Color(red: 0.08, green: 0.08, blue: 0.08)
                ],
                startPoint: .top,
                endPoint: .bottom
            )
            .ignoresSafeArea()
            .onAppear {
                // 设置默认选项
                if selectedMeatType == nil && !item.availableMeatTypes.isEmpty {
                    selectedMeatType = item.availableMeatTypes.first
                }
                if selectedSpicyLevel == nil, let spicyLevels = item.availableSpicyLevels, !spicyLevels.isEmpty {
                    selectedSpicyLevel = spicyLevels.first
                }
                if selectedPriceOption == nil {
                    selectedPriceOption = item.defaultPriceOption
                }
            }
            
            // 主要内容区域
            ScrollView(.vertical, showsIndicators: false) {
                VStack(spacing: 15) {
                    itemImageView
                        .padding(.top, 100) // 为关闭按钮留出更多空间
                    
                    VStack(alignment: .leading, spacing: 15) {
                        itemInfoSection
                        
                        priceOptionsSection
                        ingredientsSection
                        meatTypeSection
                        spicyLevelSection
                        specialInstructionsSection
                        quantitySection
                    }
                    .padding(.horizontal, 16)
                    .frame(maxWidth: 400)
                    
                    // 底部按钮区域
                    HStack(spacing: 20) {
                        Button(action: { dismiss() }) {
                            Text(dataManager.currentLanguage == "zh" ? "关闭" : "Close")
                                .font(.headline)
                                .fontWeight(.semibold)
                                .foregroundColor(.white)
                                .frame(maxWidth: 150)
                                .padding(.vertical, 16)
                                .background(
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(Color.gray)
                                )
                        }

                        Button(action: addToCart) {
                            Text(dataManager.currentLanguage == "zh" ? "添加到购物车" : "Add to Cart")
                                .font(.headline)
                                .fontWeight(.semibold)
                                .foregroundColor(Color(red: 0.12, green: 0.12, blue: 0.12))
                                .frame(maxWidth: 200)
                                .padding(.vertical, 16)
                                .background(
                                    RoundedRectangle(cornerRadius: 12)
                                        .fill(Color(red: 1.0, green: 0.6, blue: 0.2))
                                )
                        }
                        .disabled(!item.isAvailable || (!item.availableMeatTypes.isEmpty && selectedMeatType == nil) || (item.availableSpicyLevels?.isEmpty == false && selectedSpicyLevel == nil))
                        .opacity((!item.isAvailable || (!item.availableMeatTypes.isEmpty && selectedMeatType == nil) || (item.availableSpicyLevels?.isEmpty == false && selectedSpicyLevel == nil)) ? 0.6 : 1.0)
                    }
                    .padding(.horizontal, 24)
                    .padding(.top, 30)
                    .padding(.bottom, 80)
                }
            }
            .dismissKeyboardOnBackgroundTap()
        }
        
        
        .onAppear {
    if let firstMeatType = item.availableMeatTypes.first {
        selectedMeatType = firstMeatType
    }
    if let firstSpicyLevel = item.availableSpicyLevels?.first {
        selectedSpicyLevel = firstSpicyLevel
    }
    if let defaultPriceOption = item.defaultPriceOption {
        selectedPriceOption = defaultPriceOption
    } else if let firstPriceOption = item.priceOptions?.first {
        selectedPriceOption = firstPriceOption
    }
    if let window = UIApplication.shared.connectedScenes.flatMap({ ($0 as? UIWindowScene)?.windows ?? [] }).first(where: { $0.isKeyWindow }) {
        safeAreaTop = window.safeAreaInsets.top
    }
}
        .alert(isPresented: $showingAddedAlert) {
            Alert(
                title: Text(dataManager.currentLanguage == "zh" ? "已添加到购物车" : "Added to Cart"),
                message: Text("\(quantity) x \(dataManager.currentLanguage == "zh" ? item.name : item.englishName)"),
                dismissButton: .default(Text("OK")) {
                    dismiss()
                }
            )
        }
    }
    
    // MARK: - Private Views
    private var itemImageView: some View {
        MenuItemImageView(
            imageSource: item.bestImageSource,
            height: 250,
            cornerRadius: 20
        )
    }
    
    private var itemInfoSection: some View {
        VStack(alignment: .leading, spacing: 10) {
            HStack {
                Text(dataManager.currentLanguage == "zh" ? item.name : item.englishName)
                    .font(.title)
                    .fontWeight(.bold)
                    .foregroundColor(.white)
                
                Spacer()
                
                HStack(spacing: 8) {
                    if item.isSpicy {
                        Label("辣", systemImage: "flame.fill")
                            .font(.caption)
                            .foregroundColor(.red)
                    }
                    
                    if item.isVegetarian {
                        Label("素", systemImage: "leaf.fill")
                            .font(.caption)
                            .foregroundColor(.green)
                    }
                }
            }
            
            Text(dataManager.currentLanguage == "zh" ? item.description : item.englishDescription)
                .font(.body)
                .foregroundColor(.gray)
            
            // 原材料详情描述
            if let ingredientDescription = dataManager.currentLanguage == "zh" ? item.ingredientDescription : item.englishIngredientDescription, !ingredientDescription.isEmpty {
                VStack(alignment: .leading, spacing: 8) {
                    Text(dataManager.currentLanguage == "zh" ? "主要原料" : "Main Ingredient")
                        .font(.headline)
                        .fontWeight(.semibold)
                        .foregroundColor(.white)
                    
                    Text(ingredientDescription)
                        .font(.body)
                        .foregroundColor(.gray)
                        .lineLimit(nil)
                        .multilineTextAlignment(.leading)
                }
            }
            
            Text("S$\(selectedPriceOption?.price ?? item.displayPrice, specifier: "%.2f")")
                .font(.title2)
                .fontWeight(.bold)
                .foregroundColor(Color(red: 1.0, green: 0.9, blue: 0.0))
        }
    }
    
    @ViewBuilder
    private var priceOptionsSection: some View {
        if let priceOptions = item.priceOptions, !priceOptions.isEmpty {
            VStack(alignment: .leading, spacing: 10) {
                Text(dataManager.currentLanguage == "zh" ? "选择份量" : "Choose Size")
                    .font(.headline)
                    .foregroundColor(.white)
                
                VStack(spacing: 8) {
                    ForEach(priceOptions, id: \.id) { priceOption in
                        Button(action: {
                            selectedPriceOption = priceOption
                        }) {
                            HStack {
                                Text(dataManager.currentLanguage == "zh" ? priceOption.description : priceOption.englishDescription)
                                    .font(.subheadline)
                                    .foregroundColor(selectedPriceOption?.id == priceOption.id ? Color(red: 0.12, green: 0.12, blue: 0.12) : .white)
                                    .fontWeight(.medium)
                                
                                Spacer()
                                
                                Text("S$\(priceOption.price, specifier: "%.2f")")
                                    .font(.subheadline)
                                    .fontWeight(.bold)
                                    .foregroundColor(selectedPriceOption?.id == priceOption.id ? Color(red: 0.12, green: 0.12, blue: 0.12) : Color(red: 1.0, green: 0.9, blue: 0.0))
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 12)
                            .background(
                                RoundedRectangle(cornerRadius: 10)
                                    .fill(selectedPriceOption?.id == priceOption.id ? Color(red: 1.0, green: 0.6, blue: 0.2) : Color.clear)
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 10)
                                            .stroke(Color(red: 1.0, green: 0.6, blue: 0.2), lineWidth: 1.5)
                                    )
                            )
                        }
                    }
                }
            }
        }
    }
    
    @ViewBuilder
    private var ingredientsSection: some View {
        if !item.ingredients.isEmpty {
            VStack(alignment: .leading, spacing: 10) {
                Text(dataManager.currentLanguage == "zh" ? "主要配料" : "Main Ingredients")
                    .font(.headline)
                    .foregroundColor(.white)
                
                LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 2), spacing: 8) {
                    ForEach(item.ingredients, id: \.self) { ingredient in
                        Text(ingredient)
                            .font(.subheadline)
                            .foregroundColor(.gray)
                            .padding(.horizontal, 12)
                            .padding(.vertical, 6)
                            .background(
                                RoundedRectangle(cornerRadius: 8)
                                    .fill(Color(red: 0.25, green: 0.22, blue: 0.20))
                            )
                    }
                }
            }
        }
    }
    
    @ViewBuilder
    private var meatTypeSection: some View {
        if !item.availableMeatTypes.isEmpty {
            VStack(alignment: .leading, spacing: 10) {
                Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.chooseMeatType : AppStrings.Menu.chooseMeatTypeEn)
                    .font(.headline)
                    .foregroundColor(.white)
                
                HStack(spacing: 15) {
                    ForEach(item.availableMeatTypes, id: \.self) { meatType in
                        Button(action: {
                            selectedMeatType = meatType
                        }) {
                            Text(dataManager.currentLanguage == "zh" ? meatType.rawValue : meatType.englishName)
                            .font(.subheadline)
                            .foregroundColor(selectedMeatType == meatType ? Color(red: 0.12, green: 0.12, blue: 0.12) : .white)
                            .frame(maxWidth: .infinity)
                            .padding(.horizontal, 25)
                            .padding(.vertical, 12)
                            .background(
                                RoundedRectangle(cornerRadius: 8)
                                    .fill(selectedMeatType == meatType ? Color(red: 1.0, green: 0.6, blue: 0.2) : Color.clear)
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 8)
                                            .stroke(Color(red: 1.0, green: 0.6, blue: 0.2), lineWidth: 1)
                                    )
                            )
                        }
                        .frame(minWidth: 120)
                    }
                }
            }
        }
    }
    
    @ViewBuilder
    private var spicyLevelSection: some View {
        if let spicyLevels = item.availableSpicyLevels, !spicyLevels.isEmpty {
            HStack(spacing: 15) {
                ForEach(spicyLevels, id: \.self) { spicyLevel in
                    Button(action: {
                        selectedSpicyLevel = spicyLevel
                    }) {
                        Text(dataManager.currentLanguage == "zh" ? spicyLevel.rawValue : spicyLevel.englishName)
                            .font(.subheadline)
                            .foregroundColor(selectedSpicyLevel == spicyLevel ? Color(red: 0.12, green: 0.12, blue: 0.12) : .white)
                            .padding(.horizontal, 30)
                            .padding(.vertical, 12)
                            .background(
                                RoundedRectangle(cornerRadius: 8)
                                    .fill(selectedSpicyLevel == spicyLevel ? Color(red: 1.0, green: 0.6, blue: 0.2) : Color.clear)
                                    .overlay(
                                        RoundedRectangle(cornerRadius: 8)
                                            .stroke(Color(red: 1.0, green: 0.6, blue: 0.2), lineWidth: 1)
                                    )
                            )
                    }
                }
            }
        }
    }
    
    private var specialInstructionsSection: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.specialRequirement : AppStrings.Menu.specialRequirementEn)
                .font(.headline)
                .foregroundColor(.white)
            
            TextField(
                dataManager.currentLanguage == "zh" ? AppStrings.Menu.enterSpecialRequirement : AppStrings.Menu.enterSpecialRequirementEn,
                text: $specialInstructions
            )
            .foregroundColor(.white)
            .font(.body)
            .padding(.horizontal, 18)
            .padding(.vertical, 14)
            .background(
                RoundedRectangle(cornerRadius: 16)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color(red: 0.25, green: 0.15, blue: 0.08),
                                Color(red: 0.35, green: 0.22, blue: 0.12)
                            ],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .overlay(
                        RoundedRectangle(cornerRadius: 16)
                            .stroke(
                                LinearGradient(
                                    colors: [
                                        Color(red: 1.0, green: 0.8, blue: 0.4).opacity(0.3),
                                        Color(red: 1.0, green: 0.6, blue: 0.2).opacity(0.2)
                                    ],
                                    startPoint: .topLeading,
                                    endPoint: .bottomTrailing
                                ),
                                lineWidth: 1.5
                            )
                    )
                    .shadow(
                        color: Color.black.opacity(0.3),
                        radius: 8,
                        x: 0,
                        y: 4
                    )
            )
            .overlay(
                RoundedRectangle(cornerRadius: 16)
                    .fill(
                        LinearGradient(
                            colors: [
                                Color.white.opacity(0.05),
                                Color.clear
                            ],
                            startPoint: .top,
                            endPoint: .bottom
                        )
                    )
                    .allowsHitTesting(false)
            )
        }
    }
    
    private var quantitySection: some View {
        VStack(alignment: .leading, spacing: 10) {
            Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.quantity : AppStrings.Menu.quantityEn)
                .font(.headline)
                .foregroundColor(.white)
            
            HStack {
                Button(action: {
                    if quantity > 1 {
                        quantity -= 1
                    }
                }) {
                    Image(systemName: "minus.circle.fill")
                        .font(.title2)
                        .foregroundColor(quantity > 1 ? Color(red: 1.0, green: 0.9, blue: 0.0) : .gray)
                }
                .disabled(quantity <= 1)
                
                Text("\(quantity)")
                    .font(.title2)
                    .fontWeight(.semibold)
                    .foregroundColor(.white)
                    .frame(minWidth: 50)
                
                Button(action: {
                    quantity += 1
                }) {
                    Image(systemName: "plus.circle.fill")
                        .font(.title2)
                        .foregroundColor(Color(red: 1.0, green: 0.9, blue: 0.0))
                }
                
                Spacer()
                
                Text("S$\((selectedPriceOption?.price ?? item.displayPrice) * Double(quantity), specifier: "%.2f")")
                    .font(.title2)
                    .fontWeight(.bold)
                    .foregroundColor(Color(red: 1.0, green: 0.9, blue: 0.0))
            }
        }
    }
    
    private func addToCart() {
        dataManager.addToCart(
            item,
            quantity: quantity,
            meatType: selectedMeatType,
            spicyLevel: selectedSpicyLevel,
            specialInstructions: specialInstructions,
            priceOption: selectedPriceOption
        )
        showingAddedAlert = true
    }
}


// MARK: - 数量选择器组件
struct QuantitySelector: View {
    let item: MenuItem
    @EnvironmentObject var dataManager: DataManager
    
    @State private var quantity: Int = 0
    @State private var showingAddToCart = false
    @State private var isPlusPressed = false
    @State private var isMinusPressed = false
    
    var body: some View {
        HStack(spacing: 8) {
            // 减少按钮 - 始终显示
            Button(action: {
                withAnimation(.easeInOut(duration: 0.15)) {
                    isMinusPressed = true
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
                    withAnimation(.easeInOut(duration: 0.15)) {
                        isMinusPressed = false
                    }
                }
                
                if quantity > 1 {
                    quantity -= 1
                    updateCart()
                } else if quantity == 1 {
                    quantity = 0
                    dataManager.removeFromCart(item)
                }
            }) {
                Image(systemName: "minus.circle.fill")
                    .font(.title3)
                    .foregroundColor(quantity > 0 ? Color(red: 1.0, green: 0.9, blue: 0.0) : .gray) // #FFE600
                    .scaleEffect(isMinusPressed ? 0.85 : 1.0)
                    .shadow(
                        color: isMinusPressed ? Color(red: 1.0, green: 0.9, blue: 0.0).opacity(0.8) : Color.clear,
                        radius: isMinusPressed ? 12 : 0,
                        x: 0,
                        y: 0
                    )
            }
            .buttonStyle(PlainButtonStyle())
            .disabled(quantity == 0)
            
            // 数量显示 - 始终显示
            Text("\(quantity)")
                .font(.subheadline)
                .fontWeight(.semibold)
                .foregroundColor(.white)
                .frame(minWidth: 25)
            
            // 增加按钮
            Button(action: {
                withAnimation(.easeInOut(duration: 0.15)) {
                    isPlusPressed = true
                }
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
                    withAnimation(.easeInOut(duration: 0.15)) {
                        isPlusPressed = false
                    }
                }
                
                quantity += 1
                updateCart()
                if quantity == 1 {
                    showingAddToCart = true
                }
            }) {
                Image(systemName: "plus.circle.fill")
                    .font(.title2)
                    .foregroundColor(Color(red: 1.0, green: 0.9, blue: 0.0)) // #FFE600
                    .scaleEffect(isPlusPressed ? 0.85 : 1.0)
                    .shadow(
                        color: isPlusPressed ? Color(red: 1.0, green: 0.9, blue: 0.0).opacity(0.8) : Color.clear,
                        radius: isPlusPressed ? 12 : 0,
                        x: 0,
                        y: 0
                    )
            }
            .buttonStyle(PlainButtonStyle())
        }
        .onAppear {
            // 从购物车中获取当前数量
            quantity = dataManager.getItemQuantityInCart(item)
        }
        .onChange(of: dataManager.cartItems) { _ in
            // 当购物车发生变化时，更新本地数量显示
            let currentQuantity = dataManager.getItemQuantityInCart(item)
            if quantity != currentQuantity {
                quantity = currentQuantity
            }
        }
        .alert(isPresented: $showingAddToCart) {
            Alert(
                title: Text(dataManager.currentLanguage == "zh" ? AppStrings.Menu.addedToCart : AppStrings.Menu.addedToCartEn),
                message: Text(dataManager.currentLanguage == "zh" ? item.name : item.englishName),
                dismissButton: .default(Text(AppStrings.Common.confirm))
            )
        }
    }
    
    private func updateCart() {
        if quantity > 0 {
            // 如果商品不在购物车中，先添加到购物车
            if dataManager.getItemQuantityInCart(item) == 0 {
                dataManager.addToCart(item, quantity: quantity)
            } else {
                dataManager.updateCartItemQuantity(item, quantity: quantity)
            }
        } else {
            // 数量为0时从购物车移除
            dataManager.removeFromCart(item)
        }
    }
}
}

#Preview {
    let dataManager = DataManager.shared
    return MenuView()
        .environmentObject(dataManager)
}